package com.zheng.security.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zheng.security.entity.SecurityUser;
import com.zheng.security.entity.SecurityUserAuth;
import com.zheng.security.exception.ApiException;
import com.zheng.security.mapper.SecurityUserAuthMapper;
import com.zheng.security.mapper.SecurityUserMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zyq
 * @Description
 * @createTime 2021年01月15日 14:50:00
 */
@Service("userDetailsService")
public class MyUserDetailsServiceImpl implements UserDetailsService {

    private final SecurityUserMapper userMapper;
    private final SecurityUserAuthMapper authMapper;

    public MyUserDetailsServiceImpl(SecurityUserMapper userMapper, SecurityUserAuthMapper authMapper) {
        this.userMapper = userMapper;
        this.authMapper = authMapper;
    }


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //从数据库中获取用户
        QueryWrapper<SecurityUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", username);
        SecurityUser user = userMapper.selectOne(wrapper);
        if (ObjectUtils.isEmpty(user)) {
            throw new ApiException("用户名不存在");
        }
        //返回用户信息 -> 用户名 密码 权限信息
        //Set<GrantedAuthority> authorities = new HashSet<>();
        //添加角色
        QueryWrapper<SecurityUserAuth> authWrapper = new QueryWrapper<>();
        authWrapper.eq("user_id", user.getUserId());
        List<String> roleList = authMapper.selectList(authWrapper).stream().map(SecurityUserAuth::getRoleName).collect(Collectors.toList());
        List<GrantedAuthority> authorities = roleList2GrantedAuthority(roleList);
        return new User(user.getUserName(), new BCryptPasswordEncoder().encode(user.getPassword()), authorities);
    }


    private List<GrantedAuthority> roleList2GrantedAuthority(List<String> roleList){
        if (roleList.isEmpty()){
            return AuthorityUtils.createAuthorityList();
        }
        StringBuilder sb = new StringBuilder("");
        for (int i = 0; i < roleList.size(); i++) {
            if (i != roleList.size()-1){
                sb.append(roleList.get(i)).append(",");
            }else {
                sb.append(roleList.get(i));
            }
        }
        return AuthorityUtils.commaSeparatedStringToAuthorityList(sb.toString());
    }
}
